package com.ltxtiyu.video.common;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ValueFilter;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JsonTool {

    public static String genJson(RetEnum re) throws JSONException {
        return genJson(re, new HashMap<String, Object>());
    }

    public static String genJson(RetEnum re, Map<String, Object> body) throws JSONException {
        body.put("ret", re.getRet());
        body.put("msg", re.getMsg());
        return genJson(body);
    }

    public static String genJson(RetEnum re, String setKey, List<Map<String, Object>> setBody)
            throws JSONException {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("ret", re.getRet());
        map.put("msg", re.getMsg());
        map.put(setKey, setBody);
        return genJson(map);
    }

    public static String genJson(Map<String, Object> map) throws JSONException {
        /* 这种只能转换最外层的, 对于value是对象时就不行了 */
        /*JSONObject jsonObject = new JSONObject();
        for (String key : map.keySet()) {
            jsonObject.put(key, map.get(key) == null ? "" : map.get(key));
        }
        return jsonObject.toString();*/

        // fastJson 值为null时赋值为""
        String jsonString = JSONObject.toJSONString(map,
                new ValueFilter() {
                    @Override
                    public Object process(Object source, String name, Object value) {
                        if (value == null) {
                            return "";
                        }
                        if(value.getClass().equals(Date.class)){    // 时间会默认搞成字符串的
                            Date date = (Date) value;
                            return date.getTime();
                        }
                        return value;
                    }
                },
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullNumberAsZero,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullStringAsEmpty,
                SerializerFeature.WriteNullBooleanAsFalse
                );

        return jsonString;
    }

    public static JSONObject getJson(Map<String, Object> map) throws JSONException {
        JSONObject jsonObject = new JSONObject();
        for (String key : map.keySet()) {
            jsonObject.put(key, map.get(key) == null ? "" : map.get(key));
        }
        return jsonObject;
    }
}
